



const { createApp } = Vue;
const app = createApp({
    async mounted() {
        const that = this;

        // 初始化编辑器
        CyueEditor.init(true);
        // 初始化 日期控件
        const inputDateElement = this.$refs.dateInput;
        inputDateElement.valueAsDate = new Date();


        // 判断登录
        this.accessToken  = window.localStorage.getItem("token");
        if (!this.accessToken)
        {
            alert("未登录！");
            window.location.assign("./login.html");
        }

        // 判断 token 是否有效
        // axios.defaults.headers.common['token'] = this.accessToken;
        await HTTP.setHeaders({
            token: this.accessToken
        });
        HTTP.request({
            method: "GET",
            url: "/api/user/verifyToken"
        }).then(response => {
            const result = response.data;
            if (!result.data)
            {
                window.localStorage.setItem("token", null);
                window.localStorage.setItem("username", null);
                alert("认证失效！请重新登录。");
                window.location.assign("./login.html");
            }
        });


        // 初始化 转载 checkbox
        document.getElementById("input-checkbox-reprint").addEventListener("change", (e) => {
            const input = e.target;
            that.reprintCheck = input.checked;
            if (!input.checked)
            {
                document.getElementById("input-author").value = "";
            }
        });

        // 初始化 分类select
        HTTP.request({
            method: "GET",
            url: "/api/article/sort/all"
        }).then(response => {
            const result = response.data;
            const sorts = result.data;
            const selectElement = this.$refs.sortSelect;
            sorts.forEach(element => {
                const option = document.createElement("option");
                option.value = element.id;
                option.innerHTML = element.name;
                selectElement.appendChild(option);
            });
        })


    },

    data() {
        return {
            accessToken: null,
            currentPanel: "发布文章",
            reprintCheck: false,
            articleDataSource: []
        }
    },

    methods: {
        
        clickArticleManage(e)
        {
            const that = this;
            this.currentPanel = "文章管理";
            const username = window.localStorage.getItem("username");
            HTTP.request({
                method: "GET",
                url: `/api/article/user/username/${username}`
            })
            .then(response => {
                const result = response.data;
                that.articleDataSource = result.data;
            });
        },


        clickSortManage(e)
        {
            this.currentPanel = "分类管理";
        },



        clickArticlePublish(e)
        {
            this.currentPanel = "发布文章";
        },



        async clickPublishArticle(e)
        {
            const editor = this.$refs.editor;
            // console.log(editor)

            const author = document.getElementById("input-author").value;
            const title = document.getElementsByClassName("panel-input-title")[0].getElementsByTagName("input")[0].value;
            const date = document.getElementsByClassName("panel-input-date")[0].getElementsByTagName("input")[0].value;
            const sortID = document.getElementsByClassName("panel-input-sort")[0].getElementsByTagName("select")[0].value;
            let content = editor.getArticleContentXML();


            // debug
            // console.log(content);
            // return;

            if (!title)
            {
                alert("请输入标题");
                return;
            }
            if (!date)
            {
                alert("请输入日期");
                return;
            }
            if (!sortID)
            {
                alert("请选择分类");
                return;
            }
            if (!content)
            {
                alert("请输入正文内容");
                return;
            }
            if (content.length < 10)
            {
                alert("内容太少啦")
                return;
            }

            // 上传图片，替换 src
            const regexp = /<img [^>]*src=['"](?<src>[^'"]+)[^>]*>/gi;
            const regexpContent = content;
            let m = regexp.exec(regexpContent);
            let index = 1;
            let imgUpload = true;
            while(m)
            {
                // console.log(m);
                const src = m.groups.src;
                Dialog.popup(`上传第${index}张图片`);
                try {
                    const response = await HTTP.request({
                        method: "POST",
                        url: "/api/upload/base64/img",
                        headers: {
                            token: this.accessToken
                        },
                        data: {
                            data: src
                        }
                    });
                    const result = response.data;
                    if (result.type === "success") {
                        Dialog.popup(`第${index}张图片上传成功`);
                        const url = result.data;
                        content = content.replace(src, url);
                        imgUpload = true;
                    } else {
                        // console.log(result);
                        Dialog.popup(`第${index}张图片上传失败`);
                        imgUpload = false;
                    }
                } catch (e) {
                    Dialog.popup(`第${index}张图片上传失败`);
                    imgUpload = false;
                }
                
                m = regexp.exec(regexpContent);
                index++;
            }

            // 有图片上传失败
            if (!imgUpload)
            {
                alert("发布失败");
                return;
            }

            HTTP.request({
                method: "POST",
                headers: {
                    token: this.accessToken
                },
                url: "/api/article",
                data: {
                    author: author,
                    title: title,
                    date: date,
                    sort_id: parseInt(sortID),
                    content: content
                }
            }).then(response => {
                const result = response.data;
                // console.log(result);
                if (result.type === "failed")
                {
                    alert("发布失败");
                    return;
                }

                alert("发布成功");
                editor.clear();
                document.getElementsByClassName("panel-input-title")[0].getElementsByTagName("input")[0].value = "";
                document.getElementsByClassName("panel-input-date")[0].getElementsByTagName("input")[0].value = "";
            
            });
        },


    }


});
app.mount("#app");



